package com.tomas.demo.controller.xss;

import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.ssi.SSIServletRequestUtil;
import org.apache.tomcat.util.http.RequestUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Tomas
 * @date 16/7/8 上午10:31
 * @what
 */
@Slf4j
@RequestMapping(value = "/xss")
@Controller
public class XssTestController {

    @RequestMapping("")
    public String xss_in(){
        return "/xss/in";
    }

    @RequestMapping("/out")
    public String xss_out(String xssStr,HttpServletRequest request,HttpServletResponse response,Model map){

        log.info("注入 脚本:" + xssStr);
        map.addAttribute("xssStr", xssStr);
      /*  for (Cookie cookie: request.getCookies()){
           ///servlet3.0 之后默认设置httpOnly等于true
            //cookie.setHttpOnly(false);
        }*/
       //Cookie cookie = new Cookie("tomas","tomas的cookie");
        //response.addCookie(cookie);
        addCookie(response,"tomas","bbb",1800);
        addCookie(response,"sessionId",""+request.getSession().getId(),1800);
       // String sessionid = request.getSession().getId();
       // be careful overwriting: JSESSIONID may have been set with other flags
       // response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid + "; HttpOnly");
        return "/xss/out";
    }
    @RequestMapping(value = "/cookie")
    public String showCookie(String foo,String name,String password, HttpServletRequest request,HttpServletResponse response,Model map){

        log.info("获取到的 foo: {} name :{} password:{}" , foo,name,password);
        map.addAttribute("foo", foo);
        map.addAttribute("name", name);
        map.addAttribute("password", password);

        //Cookie cookie = new Cookie("tomas","tomas.cookie");
        //response.addCookie(cookie);

        addCookie(response,"tomas","cookieValue",1800);
        addCookie(response,"sessionId",""+request.getSession().getId(),1800);
        //JSESSIONID 默认会设置成httpOnly的
        // String sessionid = request.getSession().getId();
        // be careful overwriting: JSESSIONID may have been set with other flags
        // response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid + "; HttpOnly");
        return "/xss/showCookie";
    }

    /**
     * 设置cookie
     * @param response
     * @param name  cookie名字
     * @param value cookie值
     * @param maxAge cookie生命周期  以秒为单位
     */
    private static void addCookie(HttpServletResponse response,String name,String value,int maxAge){
        Cookie cookie = new Cookie(name,value);
        cookie.setPath("/");
        if(maxAge>0)  cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

}
